<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fas fa-arrow-left" @click="goBack"></i>
      <p>商家详情</p>
      <div style="width: 24px;"></div>
    </header>

    <!-- 商家logo部分 -->
    <div class="business-logo">
      <img :src="getBusinessImage(business.businessImg)" />
    </div>

    <!-- 商家信息部分 -->
    <div class="business-info">
      <h1>{{ business.businessName }}</h1>
      <div class="business-stats">
        <div class="rating">
          <div class="stars">
            <i
                v-for="n in 5"
                :key="n"
                class="fas fa-star"
                :class="{ filled: n <= Math.floor(business.rating || 0) }"
            ></i>
          </div>
          <span class="rating-score">{{ business.rating || 0 }}</span>
          <span class="month-sales">月售{{ business.monthSales || 0 }}单</span>
        </div>
      </div>
      <p class="delivery-info">
        &#165;{{ business.startPrice }}起送 | &#165;{{ business.deliveryPrice }}配送
      </p>
      <p class="business-description">{{ business.businessExplain }}</p>

      <div class="business-details">
        <div class="detail-item">
          <i class="fas fa-clock"></i>
          <span>配送时间: {{ business.deliveryTime || '30' }}分钟</span>
        </div>
        <div class="detail-item">
          <i class="fas fa-map-marker-alt"></i>
          <span>{{ business.businessAddress }}</span>
        </div>
        <div class="detail-item" v-if="business.businessPhone">
          <i class="fas fa-phone"></i>
          <span>{{ business.businessPhone }}</span>
        </div>
      </div>

      <!-- 商家活动 -->
      <div class="business-activities" v-if="business.activities && business.activities.length > 0">
        <h3>商家活动</h3>
        <div
            v-for="(activity, index) in business.activities"
            :key="index"
            class="activity-item"
        >
          <span class="activity-icon" :style="{ backgroundColor: getActivityColor(activity.type) }">
            {{ getActivityIcon(activity.type) }}
          </span>
          <span class="activity-content">{{ activity.content }}</span>
        </div>
      </div>
    </div>

    <!-- 食品列表部分 -->
    <div class="food-section">
      <h3>商品列表</h3>
      <ul class="food-list">
        <template v-for="food in foodArr" :key="food.id">
          <li class="food-item" v-if="food.deleted === false||food.deleted === null">
            <div class="food-left">
              <img :src="getFoodImage(food.foodImg)" :alt="food.foodName" />
              <div class="food-info">
                <h4>{{ food.foodName || '商品信息加载中...' }}</h4>
                <p class="food-description">{{ food.foodExplain || '暂无描述' }}</p>
                <p class="food-price">&#165;{{ formatPrice(food.foodPrice) }}</p>
                <p class="food-sales" v-if="food.monthSales">月售{{ food.monthSales }}份</p>
              </div>
            </div>
            <div class="food-right">
              <div class="quantity-control">
                <button
                    class="btn minus"
                    @click="minus(food.id)"
                    :disabled="getFoodQuantity(food.id) === 0"
                    :class="{ disabled: getFoodQuantity(food.id) === 0 }"
                >
                  <i class="fas fa-minus"></i>
                </button>
                <span class="quantity" v-show="getFoodQuantity(food.id) > 0">
            {{ getFoodQuantity(food.id) }}
          </span>
                <button class="btn plus" @click="add(food.id)">
                  <i class="fas fa-plus"></i>
                </button>
              </div>
            </div>
          </li>
        </template>
      </ul>

      <!-- 空状态 -->
      <div class="empty-food" v-if="foodArr.length === 0 && !foodLoading">
        <i class="fas fa-utensils"></i>
        <p>暂无商品</p>
      </div>

      <!-- 加载状态 -->
      <div class="loading-food" v-if="foodLoading">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载商品中...</span>
      </div>
    </div>

    <!-- 购物车部分 -->
    <div class="cart" :class="{ active: totalQuantity > 0 }">
      <div class="cart-left">
        <div class="cart-icon" :class="{ hasItems: totalQuantity > 0 }">
          <i class="fas fa-shopping-cart"></i>
          <div class="cart-quantity" v-if="totalQuantity > 0">{{ totalQuantity }}</div>
        </div>
        <div class="cart-info">
          <p class="total-price">&#165;{{ formatPrice(totalPrice) }}</p>
          <p class="delivery-fee">另需配送费{{ business.deliveryPrice }}元</p>
        </div>
      </div>
      <div class="cart-right">
        <!-- 不够起送费 -->
        <div
            class="checkout-btn disabled"
            v-if="totalSettle < business.startPrice"
        >
          &#165;{{ business.startPrice }}起送
        </div>
        <!-- 达到起送费 -->
        <div
            class="checkout-btn"
            v-else
            @click="toOrder"
        >
          去结算
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { businessAPI } from '@/api/business.js';
import { foodAPI } from '@/api/food.js';
import { cartAPI } from '@/api/cart.js';

const route = useRoute();
const router = useRouter();

const businessId = ref(route.query.businessId);
const business = ref({});
const foodArr = ref([]);
const foodLoading = ref(false);
const cartItems = ref([]); // 存储购物车数据

// 监听路由变化，当businessId变化时重新加载数据
watch(() => route.query.businessId, (newBusinessId) => {
  if (newBusinessId && newBusinessId !== businessId.value) {
    businessId.value = newBusinessId;
    loadAllData();
  }
});

// 页面加载时获取数据
onMounted(async () => {
  await loadAllData();
});

// 加载所有数据
const loadAllData = async () => {
  await loadBusinessInfo();
  await loadFoods();
  await loadCartItems();
};

// 加载商家信息
const loadBusinessInfo = async () => {
  try {
    const response = await businessAPI.getBusiness(businessId.value);

    if (response.data && response.data.success === true && response.data.data) {
      business.value = response.data.data;
    } else if (response.data) {
      business.value = response.data;
    }

    // 添加模拟数据
    business.value.rating = parseFloat((Math.random() * 2 + 3).toFixed(1));
    business.value.monthSales = Math.floor(Math.random() * 1000) + 100;
    business.value.deliveryTime = Math.floor(Math.random() * 20) + 20;
    business.value.activities = [
      { type: 'new', content: '新用户立减15元' },
      { type: 'discount', content: '满30减5元' },
      { type: 'special', content: '特价商品5元起' }
    ].slice(0, Math.floor(Math.random() * 3) + 1);

  } catch (error) {
    console.error('获取商家信息失败:', error);
    alert('获取商家信息失败');
  }
};

// 加载商品列表 - 修复参数传递问题
const loadFoods = async () => {
  foodLoading.value = true;
  try {
    // 传递必需的参数
    // console.log(businessId.value)
    const response = await foodAPI.getAllFoods(businessId.value, 1); // orderId随便传一个数

    let foods = [];
    if (response.data && response.data.success === true && response.data.data) {
      foods = response.data.data;
    } else if (response.data) {
      foods = response.data;
    }

    // console.log('所有商品:', foods);
    // console.log('当前商家ID:', businessId.value);

    // 根据商家ID筛选商品 - 移除随机筛选
    foodArr.value = foods
        .filter(food => {
          // 确保food和food.business存在
          if (!food || !food.business) return false;
          return food.business.id == businessId.value;
        })
        .map(food => ({
          ...food,
          monthSales: Math.floor(Math.random() * 100) + 10
        }));

    // console.log('筛选后的商品:', foodArr.value);

  } catch (error) {
    console.error('获取商品列表失败:', error);
  } finally {
    foodLoading.value = false;
  }
};

// 加载购物车商品 - 添加错误处理和数据验证
const loadCartItems = async () => {
  try {
    const response = await cartAPI.getCartItems();
    // console.log('购物车原始响应:', response);

    let cartData = [];
    if (response.data && response.data.success === true && response.data.data) {
      cartData = response.data.data;
    } else if (response.data) {
      cartData = response.data;
    }

    // 验证购物车数据格式
    cartItems.value = Array.isArray(cartData) ? cartData : [];

    // console.log('处理后的购物车数据:', cartItems.value);

    // 验证当前商家的购物车商品
    const currentBusinessItems = cartItems.value.filter(item =>
        item.business && item.business.id == businessId.value
    );
    // console.log('当前商家购物车商品:', currentBusinessItems);

  } catch (error) {
    console.error('获取购物车失败:', error);
    cartItems.value = [];
  }
};

// 获取商品在购物车中的数量 - 添加数据验证
const getFoodQuantity = (foodId) => {
  try {
    const cartItem = cartItems.value.find(item =>
        item && item.food && item.food.id === foodId
    );
    return cartItem ? (cartItem.quantity || 0) : 0;
  } catch (error) {
    console.error('获取商品数量失败:', error);
    return 0;
  }
};

// 计算属性 - 添加数据验证
const totalPrice = computed(() => {
  try {
    return cartItems.value
        .filter(item =>
            item && item.business && item.business.id == businessId.value &&
            item.food && item.food.foodPrice
        )
        .reduce((sum, item) => {
          const price = parseFloat(item.food.foodPrice) || 0;
          const quantity = item.quantity || 0;
          return sum + (price * quantity);
        }, 0);
  } catch (error) {
    console.error('计算总价失败:', error);
    return 0;
  }
});

const totalQuantity = computed(() => {
  try {
    return cartItems.value
        .filter(item => item && item.business && item.business.id == businessId.value)
        .reduce((sum, item) => sum + (item.quantity || 0), 0);
  } catch (error) {
    console.error('计算总数失败:', error);
    return 0;
  }
});

const totalSettle = computed(() => {
  const deliveryPrice = parseFloat(business.value.deliveryPrice) || 0;
  return totalPrice.value + deliveryPrice;
});

// 获取商家图片
const getBusinessImage = (imagePath) => {
  if (!imagePath) {
    return require('@/assets/sj01.png');
  }
  return imagePath;
};

// 获取商品图片
const getFoodImage = (imagePath) => {
  if (!imagePath) {
    return require('@/assets/sp01.png');
  }
  return imagePath;
};

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00';
  const num = parseFloat(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 获取活动颜色
const getActivityColor = (type) => {
  const colorMap = {
    'new': '#70bc46',
    'discount': '#ff5339',
    'special': '#f1884f'
  };
  return colorMap[type] || '#70bc46';
};

// 获取活动图标
const getActivityIcon = (type) => {
  const iconMap = {
    'new': '新',
    'discount': '减',
    'special': '特'
  };
  return iconMap[type] || '新';
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 增加商品数量
const add = async (foodId) => {
  try {
    // 查找商品信息
    const food = foodArr.value.find(f => f.id === foodId);
    if (!food) {
      alert('商品不存在');
      return;
    }

    console.log('添加商品到购物车:', { foodId, businessId: businessId.value });

    // 添加到购物车
    const response = await cartAPI.addCartItem({
      food:{
        id:food.id,
      },
      quantity: 1,
      businessId: {
        id:businessId.value,
      }
    });

    console.log('添加购物车响应:', response);

    // 重新加载购物车数据
    await loadCartItems();

  } catch (error) {
    console.error('添加商品到购物车失败:', error);
    alert('操作失败，请重试');
  }
};

const minus = async (foodId) => {
  // 通过foodId查找对应的foodItem
  const foodItem = foodArr.value.find(item => item.id === foodId);
  console.log(foodItem);
  if (!foodItem) return;

  // 从cartItems中查找对应的商品
  const cartItem = cartItems.value.find(item => item.food.id === foodId);
  console.log(cartItem);
  if (!cartItem || cartItem.quantity === 0) return;

  try {
    if (cartItem.quantity === 1) {
      // 从购物车删除
      await cartAPI.removeCartItem(foodId);

      // 从cartItems中移除该项
      const cartIndex = cartItems.value.findIndex(item => item.food.id === foodId);
      if (cartIndex !== -1) {
        cartItems.value.splice(cartIndex, 1);
      }
    } else {
      // 减少数量 - 使用cartItem的quantity
      const response = await cartAPI.updateCartItemQuantity(foodId, {quantity:cartItem.quantity - 1});

      // 更新cartItems中的数量
      cartItem.quantity -= 1;
    }



  } catch (error) {
    console.error('操作购物车失败:', error);
    alert('操作失败，请重试');
  }
};

// 去结算
const toOrder = () => {
  if (totalQuantity.value === 0) {
    alert('请先选择商品');
    return;
  }

  const startPrice = parseFloat(business.value.startPrice) || 0;
  if (totalSettle.value < startPrice) {
    alert(`未达到起送价¥${startPrice}`);
    return;
  }

  router.push({
    path: '/orders',
    query: {
      businessId: businessId.value
    }
  });
};
</script>

<style scoped>
/* 样式保持不变，与您提供的相同 */
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  padding-bottom: 14vw; /* 为购物车留出空间 */
}

/* Header样式 */
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
  box-sizing: border-box;
}

.wrapper header i {
  font-size: 5vw;
  cursor: pointer;
}

.wrapper header p {
  margin: 0;
  font-weight: bold;
}

/* 商家logo部分 */
.wrapper .business-logo {
  width: 100%;
  height: 35vw;
  margin-top: 12vw;
  display: flex;
  justify-content: center;
  align-items: center;
  background: white;
  padding: 4vw;
  box-sizing: border-box;
}

.wrapper .business-logo img {
  width: 40vw;
  height: 30vw;
  border-radius: 2vw;
  object-fit: cover;
}

/* 商家信息部分 */
.wrapper .business-info {
  width: 100%;
  background: white;
  padding: 4vw;
  box-sizing: border-box;
  margin-bottom: 3vw;
}

.wrapper .business-info h1 {
  font-size: 5vw;
  color: #333;
  margin: 0 0 3vw 0;
}

.wrapper .business-info .business-stats {
  margin-bottom: 3vw;
}

.wrapper .business-info .business-stats .rating {
  display: flex;
  align-items: center;
}

.wrapper .business-info .business-stats .rating .stars {
  display: flex;
  margin-right: 2vw;
}

.wrapper .business-info .business-stats .rating .stars i {
  font-size: 3.5vw;
  color: #ddd;
  margin-right: 0.5vw;
}

.wrapper .business-info .business-stats .rating .stars i.filled {
  color: #ffb400;
}

.wrapper .business-info .business-stats .rating .rating-score {
  font-size: 3.5vw;
  color: #ffb400;
  font-weight: bold;
  margin-right: 3vw;
}

.wrapper .business-info .business-stats .rating .month-sales {
  font-size: 3.5vw;
  color: #666;
}

.wrapper .business-info .delivery-info {
  font-size: 3.5vw;
  color: #666;
  margin: 0 0 2vw 0;
}

.wrapper .business-info .business-description {
  font-size: 3.2vw;
  color: #999;
  margin: 0 0 4vw 0;
  line-height: 1.5;
}

.wrapper .business-info .business-details {
  margin-bottom: 4vw;
}

.wrapper .business-info .business-details .detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
  font-size: 3.2vw;
  color: #666;
}

.wrapper .business-info .business-details .detail-item i {
  margin-right: 2vw;
  color: #0097ff;
  width: 4vw;
  text-align: center;
}

.wrapper .business-info .business-activities {
  border-top: 1px solid #f0f0f0;
  padding-top: 3vw;
}

.wrapper .business-info .business-activities h3 {
  font-size: 4vw;
  color: #333;
  margin: 0 0 3vw 0;
}

.wrapper .business-info .business-activities .activity-item {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
}

.wrapper .business-info .business-activities .activity-item .activity-icon {
  width: 5vw;
  height: 5vw;
  border-radius: 1vw;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5vw;
  margin-right: 2vw;
}

.wrapper .business-info .business-activities .activity-item .activity-content {
  font-size: 3.2vw;
  color: #666;
}

/* 食品列表部分 */
.wrapper .food-section {
  background: white;
  padding: 4vw;
  box-sizing: border-box;
}

.wrapper .food-section h3 {
  font-size: 4.5vw;
  color: #333;
  margin: 0 0 4vw 0;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 2vw;
}

.wrapper .food-section .food-list {
  width: 100%;
}

.wrapper .food-section .food-list .food-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 3vw 0;
  border-bottom: 1px solid #f0f0f0;
}

.wrapper .food-section .food-list .food-item:last-child {
  border-bottom: none;
}

.wrapper .food-section .food-list .food-item .food-left {
  display: flex;
  align-items: flex-start;
  flex: 1;
}

.wrapper .food-section .food-list .food-item .food-left img {
  width: 20vw;
  height: 20vw;
  border-radius: 2vw;
  object-fit: cover;
  margin-right: 3vw;
}

.wrapper .food-section .food-list .food-item .food-left .food-info {
  flex: 1;
}

.wrapper .food-section .food-list .food-item .food-left .food-info h4 {
  font-size: 4vw;
  color: #333;
  margin: 0 0 1vw 0;
}

.wrapper .food-section .food-list .food-item .food-left .food-info .food-description {
  font-size: 3.2vw;
  color: #999;
  margin: 0 0 1vw 0;
  line-height: 1.3;
}

.wrapper .food-section .food-list .food-item .food-left .food-info .food-price {
  font-size: 4vw;
  color: #ff4757;
  font-weight: bold;
  margin: 0 0 1vw 0;
}

.wrapper .food-section .food-list .food-item .food-left .food-info .food-sales {
  font-size: 2.8vw;
  color: #999;
  margin: 0;
}

.wrapper .food-section .food-list .food-item .food-right {
  display: flex;
  align-items: center;
}

.wrapper .food-section .food-list .food-item .food-right .quantity-control {
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 2vw;
  overflow: hidden;
}

.wrapper .food-section .food-list .food-item .food-right .quantity-control .btn {
  width: 8vw;
  height: 8vw;
  border: none;
  background: transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 3.5vw;
  color: #0097ff;
}

.wrapper .food-section .food-list .food-item .food-right .quantity-control .btn.disabled {
  color: #ccc;
  cursor: not-allowed;
}

.wrapper .food-section .food-list .food-item .food-right .quantity-control .quantity {
  padding: 0 3vw;
  font-size: 3.5vw;
  font-weight: bold;
  min-width: 8vw;
  text-align: center;
}

/* 空状态和加载状态 */
.wrapper .food-section .empty-food,
.wrapper .food-section .loading-food {
  text-align: center;
  padding: 10vw;
  color: #999;
}

.wrapper .food-section .empty-food i,
.wrapper .food-section .loading-food i {
  font-size: 8vw;
  margin-bottom: 3vw;
}

.wrapper .food-section .empty-food p,
.wrapper .food-section .loading-food span {
  font-size: 3.5vw;
}

.wrapper .food-section .loading-food i {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 购物车部分 */
.wrapper .cart {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #333;
  display: flex;
  align-items: center;
  padding: 2vw 4vw;
  z-index: 1000;
}

.wrapper .cart.active {
  background: #3d3d3d;
}

.wrapper .cart .cart-left {
  display: flex;
  align-items: center;
  flex: 2;
}

.wrapper .cart .cart-left .cart-icon {
  width: 12vw;
  height: 12vw;
  background: #666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-right: 3vw;
}

.wrapper .cart .cart-left .cart-icon.hasItems {
  background: #0097ff;
}

.wrapper .cart .cart-left .cart-icon i {
  font-size: 6vw;
  color: white;
}

.wrapper .cart .cart-left .cart-icon .cart-quantity {
  position: absolute;
  top: -2vw;
  right: -2vw;
  background: #ff4757;
  color: white;
  border-radius: 50%;
  width: 5vw;
  height: 5vw;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5vw;
  font-weight: bold;
}

.wrapper .cart .cart-left .cart-info .total-price {
  font-size: 4.5vw;
  color: white;
  font-weight: bold;
  margin: 0 0 0.5vw 0;
}

.wrapper .cart .cart-left .cart-info .delivery-fee {
  font-size: 2.8vw;
  color: #999;
  margin: 0;
}

.wrapper .cart .cart-right {
  flex: 1;
}

.wrapper .cart .cart-right .checkout-btn {
  background: #00d762;
  color: white;
  padding: 3vw;
  text-align: center;
  border-radius: 2vw;
  font-size: 4vw;
  font-weight: bold;
  cursor: pointer;
}

.wrapper .cart .cart-right .checkout-btn.disabled {
  background: #535356;
  color: #999;
  cursor: not-allowed;
}
</style>